package com.example.myapplication1.ui.library;

import android.app.Dialog;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication1.R;
import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;

import java.util.Map;

public class LibraryFragment extends Fragment {
    private static final String TAG = "LibraryFragment";
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private TextView catFoodStockText;
    private TextView freezeDriedStockText;
    private TextView catTreatsStockText;
    private Map<String, Integer> userFeedStock;
    private long userId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databaseHelper = new DatabaseHelper(requireContext());
        preferenceManager = new PreferenceManager(requireContext());
        userId = preferenceManager.getUserId();
        Log.e(TAG, "onCreate - User ID: " + userId);





        
        if (userId <= 0) {
            Log.e(TAG, "Invalid user ID: " + userId);
            Toast.makeText(requireContext(), "用户未登录或ID无效", Toast.LENGTH_SHORT).show();
            requireActivity().getSupportFragmentManager().popBackStack();
            return;
        }
        
        // 检查并初始化用户饲料库存
        databaseHelper.checkAndInitializeUserFeedStock(userId);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_library, container, false);

        // 初始化视图
        initViews(view);
        // 加载用户饲料库存
        loadUserFeedStock();
        // 设置返回按钮
        setupBackButton(view);
        // 设置喂养按钮点击事件
        setupFeedButtons(view);

        return view;
    }

    private void initViews(View view) {
        catFoodStockText = view.findViewById(R.id.cat_food_stock);
        freezeDriedStockText = view.findViewById(R.id.freeze_dried_stock);
        catTreatsStockText = view.findViewById(R.id.cat_treats_stock);
    }

    private void loadUserFeedStock() {
        userFeedStock = databaseHelper.getUserFeedStock(userId);
        Log.e(TAG, "loadUserFeedStock - Current feed stock: " + userFeedStock.toString());
        
        // 更新库存显示
        catFoodStockText.setText(userFeedStock.getOrDefault("营养猫粮", 0) + "份");
        freezeDriedStockText.setText(userFeedStock.getOrDefault("小猫冻干", 0) + "份");
        catTreatsStockText.setText(userFeedStock.getOrDefault("营养猫条", 0) + "份");
    }

    private void setupBackButton(View view) {
        ImageButton backButton = view.findViewById(R.id.back_button);
        backButton.setOnClickListener(v -> requireActivity().getSupportFragmentManager().popBackStack());
    }

    private void setupFeedButtons(View view) {
        // 设置每只猫的喂养按钮点击事件
        Button feedNaichaButton = view.findViewById(R.id.feed_naicha_button);
        Button feedDiandianButton = view.findViewById(R.id.feed_diandian_button);
        Button feedJuziButton = view.findViewById(R.id.feed_juzi_button);

        feedNaichaButton.setOnClickListener(v -> showFeedingDialog(1, "奶茶"));
        feedDiandianButton.setOnClickListener(v -> showFeedingDialog(2, "点点"));
        feedJuziButton.setOnClickListener(v -> showFeedingDialog(3, "橘子"));
    }

    private void showFeedingDialog(int catId, String catName) {
        final Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_feeding);

        // 设置标题
        TextView titleText = dialog.findViewById(R.id.dialog_title);
        titleText.setText(getString(R.string.feed_dialog_title, catName));

        // 获取输入框和库存显示
        EditText catFoodAmount = dialog.findViewById(R.id.cat_food_amount);
        EditText freezeDriedAmount = dialog.findViewById(R.id.freeze_dried_amount);
        EditText catTreatsAmount = dialog.findViewById(R.id.cat_treats_amount);

        TextView catFoodStockText = dialog.findViewById(R.id.cat_food_stock_text);
        TextView freezeDriedStockText = dialog.findViewById(R.id.freeze_dried_stock_text);
        TextView catTreatsStockText = dialog.findViewById(R.id.cat_treats_stock_text);

        // 显示当前库存
        catFoodStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫粮", 0)));
        freezeDriedStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("小猫冻干", 0)));
        catTreatsStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫条", 0)));

        // 设置按钮点击事件
        Button cancelButton = dialog.findViewById(R.id.btn_cancel);
        Button confirmButton = dialog.findViewById(R.id.btn_confirm);

        cancelButton.setOnClickListener(v -> dialog.dismiss());
        confirmButton.setOnClickListener(v -> {
            try {
                // 获取输入的数量
                String catFoodStr = catFoodAmount.getText().toString();
                String freezeDriedStr = freezeDriedAmount.getText().toString();
                String catTreatsStr = catTreatsAmount.getText().toString();

                Log.d(TAG, "Feeding attempt - Cat: " + catName + " (ID: " + catId + ")");
                Log.d(TAG, "Input amounts - Cat Food: " + catFoodStr + 
                         ", Freeze Dried: " + freezeDriedStr + 
                         ", Cat Treats: " + catTreatsStr);

                // 检查是否至少输入了一个数量
                if (TextUtils.isEmpty(catFoodStr) && 
                    TextUtils.isEmpty(freezeDriedStr) && 
                    TextUtils.isEmpty(catTreatsStr)) {
                    Toast.makeText(requireContext(), R.string.feed_amount_empty, Toast.LENGTH_SHORT).show();
                    return;
                }

                // 验证输入数量是否合法
                boolean isValid = true;
                String errorMessage = "";

                // 检查营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    try {
                        int amount = Integer.parseInt(catFoodStr);
                        Log.d(TAG, "Validating cat food - Amount: " + amount + 
                                 ", Stock: " + userFeedStock.getOrDefault("营养猫粮", 0));
                        if (amount <= 0) {
                            isValid = false;
                            errorMessage = "请输入大于0的数量";
                        } else {
                            int stock = userFeedStock.getOrDefault("营养猫粮", 0);
                            if (amount > stock) {
                                isValid = false;
                                errorMessage = getString(R.string.insufficient_cat_food);
                            }
                        }
                    } catch (NumberFormatException e) {
                        isValid = false;
                        errorMessage = "请输入有效的数量";
                        Log.e(TAG, "Invalid cat food amount", e);
                    }
                }

                // 检查小猫冻干
                if (!TextUtils.isEmpty(freezeDriedStr)) {
                    try {
                        int amount = Integer.parseInt(freezeDriedStr);
                        Log.d(TAG, "Validating freeze dried - Amount: " + amount + 
                                 ", Stock: " + userFeedStock.getOrDefault("小猫冻干", 0));
                        if (amount <= 0) {
                            isValid = false;
                            errorMessage = "请输入大于0的数量";
                        } else {
                            int stock = userFeedStock.getOrDefault("小猫冻干", 0);
                            if (amount > stock) {
                                isValid = false;
                                errorMessage = getString(R.string.insufficient_freeze_dried);
                            }
                        }
                    } catch (NumberFormatException e) {
                        isValid = false;
                        errorMessage = "请输入有效的数量";
                        Log.e(TAG, "Invalid freeze dried amount", e);
                    }
                }

                // 检查营养猫条
                if (!TextUtils.isEmpty(catTreatsStr)) {
                    try {
                        int amount = Integer.parseInt(catTreatsStr);
                        Log.d(TAG, "Validating cat treats - Amount: " + amount + 
                                 ", Stock: " + userFeedStock.getOrDefault("营养猫条", 0));
                        if (amount <= 0) {
                            isValid = false;
                            errorMessage = "请输入大于0的数量";
                        } else {
                            int stock = userFeedStock.getOrDefault("营养猫条", 0);
                            if (amount > stock) {
                                isValid = false;
                                errorMessage = getString(R.string.insufficient_cat_treats);
                            }
                        }
                    } catch (NumberFormatException e) {
                        isValid = false;
                        errorMessage = "请输入有效的数量";
                        Log.e(TAG, "Invalid cat treats amount", e);
                    }
                }

                if (!isValid) {
                    Toast.makeText(requireContext(), errorMessage, Toast.LENGTH_SHORT).show();
                    return;
                }

                boolean success = true;

                // 处理营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    try {
                        int amount = Integer.parseInt(catFoodStr);
                        if (amount > 0) {
                            if (amount <= userFeedStock.getOrDefault("营养猫粮", 0)) {
                                success &= databaseHelper.recordFeeding(userId, catId, "营养猫粮", amount);
                            } else {
                                Toast.makeText(requireContext(), R.string.insufficient_cat_food, Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(requireContext(), "请输入有效的数量", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                // 处理小猫冻干
                if (!TextUtils.isEmpty(freezeDriedStr)) {
                    try {
                        int amount = Integer.parseInt(freezeDriedStr);
                        if (amount > 0) {
                            if (amount <= userFeedStock.getOrDefault("小猫冻干", 0)) {
                                success &= databaseHelper.recordFeeding(userId, catId, "小猫冻干", amount);
                            } else {
                                Toast.makeText(requireContext(), R.string.insufficient_freeze_dried, Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(requireContext(), "请输入有效的数量", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                // 处理营养猫条
                if (!TextUtils.isEmpty(catTreatsStr)) {
                    try {
                        int amount = Integer.parseInt(catTreatsStr);
                        if (amount > 0) {
                            if (amount <= userFeedStock.getOrDefault("营养猫条", 0)) {
                                success &= databaseHelper.recordFeeding(userId, catId, "营养猫条", amount);
                            } else {
                                Toast.makeText(requireContext(), R.string.insufficient_cat_treats, Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(requireContext(), "请输入有效的数量", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if (success) {
                    Toast.makeText(requireContext(), R.string.feed_success, Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    // 重新加载库存
                    loadUserFeedStock();
                } else {
                    Toast.makeText(requireContext(), R.string.feed_failed, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error during feeding", e);
                Toast.makeText(requireContext(), "喂养失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 